package com.myself.community.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 服务层日志记录：记录用户访问日志
 */
@Slf4j
@Component
@Aspect
public class ServiceLogAspect {

    @Pointcut("execution(* com.myself.community.service.*.*(..))")
    public void pointcut() {}

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        // 用户[1.2.3.4],在[xxx],访问了[com.myself.community.service.xxx()].
        //获取request对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if(attributes==null)
            return;
        HttpServletRequest request = attributes.getRequest();
        //获取ip
        String ip = request.getRemoteHost();
        //获取日期
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //反射获取了类名、方法名
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        //打印日志
        //log.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
    }

}
